import { Injectable } from '@angular/core';
import { Http, RequestOptions,Headers } from "@angular/http";
import { Hero, HEROS } from "./hero";
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';

@Injectable()
export class HeroService {

  private heroesUrl = 'api/heroes';  // URL to web api
  constructor(private http:Http) { }
  getHeroes():Hero[]{
    return HEROS;
  }
  getHeroes2():Promise<Hero[]>{
    return Promise.resolve(HEROS);
  }
  getHeroes3():Promise<Hero[]>{
    return this.http.get(this.heroesUrl).toPromise()
    .then(response=>response.json() as Hero[])
    .catch(this.handleError);
  }
  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }
  getHero(id:number):Promise<Hero>{
    return this.getHeroes2().then(heroes => heroes.find(hero => hero.id === id));
  }
  getHero2(id:number):Hero{
    return this.getHeroes().find(hero => hero.id === id);
  }
  getHero3(id:number):Promise<Hero>{
    return this.http.get(this.heroesUrl).toPromise()
    .then(response=>response.json().data as Hero)
    .catch(this.handleError);
  }
  // getHero(id:string): Hero{
  //   let tid = Number(id);
  //   return this.getHeroes().find((hero=>hero.id === tid));
  // }
  private headers = new Headers({'Content-Type': 'application/json'});

  //new RequestOptions(headers: this.headers1)
  private headers1: Headers = new Headers({"Content-Type'" : 'application/json',
                            'Accept': 'application/json',
                            'Access-Control-Allow-Origin':'*',
                            'Access-Control-Allow-Credentials':'true'
                            });
  update(hero: Hero): Observable<Hero> {
    let myParams = new URLSearchParams();
    let options = new RequestOptions({headers: this.headers, params: myParams });
    const url = `${this.heroesUrl}/${hero.id}`;
    return this.http
              .post(url, JSON.stringify(hero), options)
              .map(response  => response.json() as Hero);
  }
  create(id:number,name: string): Observable<Hero> {
    let myParams = new URLSearchParams();
    let options = new RequestOptions({headers: this.headers, params: myParams });
    return this.http
      .post(this.heroesUrl, JSON.stringify({id:id,name: name}),{headers: this.headers, params: myParams })
      .map(res => res.json() as Hero);
  }
  create2(id:number,name: string): Promise<Hero> {
    return this.http
      .post(this.heroesUrl, JSON.stringify({id:id,name: name}), {headers: this.headers})
      .toPromise()
      .then(res => res.json() as Hero)
      .catch(this.handleError);
  }
  delete(id: number): Observable<void> {
    let myParams = new URLSearchParams();
    let options = new RequestOptions({headers: this.headers, params: myParams });
    const url = `${this.heroesUrl}/${id}`;
    return this.http.delete(url, options)
      .map(() => null);
  }
}
